﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConfeccionesJR.Entites;
using System.Data;
using System.Data.Objects;

namespace ConfeccionesJR.Repository
{
    public class CreditoRepository: MasterDataAccess, ICreditoRepository
    {
        public List<CREDITO> GetAllFromCreditos()
        {
            var query = from c in Context.CREDITOes.Include("CLIENTE")
                       // orderby c.FechaCredito descending
                        select c;
            ObjectContext.Refresh(RefreshMode.StoreWins, query);

            return query.ToList();
        }

        public List<CREDITO> GetFromCreditobyCliente(string cliente)
        {
            if (cliente != "")
            {
                var hoy = DateTime.Today.Date;
                var query = from v in Context.CREDITOes.Include("CLIENTE")
                            where v.CLIENTE.DniRuc.ToUpper().Contains(cliente.ToUpper()) ||
                                    v.CLIENTE.NombreRazonSocial.ToUpper().Contains(cliente.ToUpper())
                            where v.FechaCredito == hoy
                            select v;

                ObjectContext.Refresh(RefreshMode.StoreWins, query);

                return query.ToList();
            }
            else
            {
                var query = from v in Context.CREDITOes.Include("CLIENTE")
                            select v;

                ObjectContext.Refresh(RefreshMode.StoreWins, query);

                return query.ToList();
            }
        }

        public List<CREDITO> GetFromCreditobyFechaAndCliente(DateTime? fec1, DateTime? fec2, string cliente)
        {
            if (cliente != "")
            {
                var query = from h in Context.CREDITOes.Include("CLIENTE")
                            select h;

                ObjectContext.Refresh(RefreshMode.StoreWins, query);


                if (fec1 != null && fec2 != null)//ambos
                {
                    query = from h in query
                            where (h.FechaCredito >= fec1.Value && h.FechaCredito <= fec2.Value) &&
                                    h.CLIENTE.NombreRazonSocial.ToUpper().Contains(cliente.ToUpper())
                            select h;

                    ObjectContext.Refresh(RefreshMode.StoreWins, query);


                }
                if (fec1 != null && fec2 == null)//solo cliente
                {
                    query = from h in query
                            where h.FechaCredito == fec1.Value &&
                                    h.CLIENTE.NombreRazonSocial.ToUpper().Contains(cliente.ToUpper())
                            select h;

                    ObjectContext.Refresh(RefreshMode.StoreWins, query);


                }
                else //retornar todos
                {
                    query = from h in query
                            select h;

                    ObjectContext.Refresh(RefreshMode.StoreWins, query);


                }
                return query.Take(500).ToList();
            }
            else
            {
                var query = from h in Context.CREDITOes.Include("CLIENTE")
                            select h;
                
                    ObjectContext.Refresh(RefreshMode.StoreWins, query);



                if (fec1 != null && fec2 != null)//solo fecha
                {
                    query = from h in query
                            where h.FechaCredito >= fec1.Value && h.FechaCredito <= fec2.Value
                            select h;

                    ObjectContext.Refresh(RefreshMode.StoreWins, query);

                }
                if (fec1 != null && fec2 == null)//solo cliente
                {
                    query = from h in query
                            where h.FechaCredito == fec1.Value 
                            select h;

                    ObjectContext.Refresh(RefreshMode.StoreWins, query);

                }
                return query.Take(500).ToList();
            }
        }

        public CREDITO GetFromCreditoById(int id)
        {
            var query = from dv in Context.CREDITOes.Include("DETALLE_CREDITO.PRODUCTO").Include("DETALLEPAGOes")
                        where dv.Id.Equals(id)
                        select dv;
            
            ObjectContext.Refresh(RefreshMode.StoreWins, query);

            return query.SingleOrDefault();
        }

        public void AddCredito(CREDITO credito)
        {
            foreach (var item in credito.DETALLE_CREDITO)
            {
                Context.Entry(item.PRODUCTO).State = EntityState.Unchanged;
                Context.Entry(item).State = EntityState.Added;
            }

            Context.Entry(credito.CLIENTE).State = EntityState.Unchanged;
            Context.CREDITOes.Add(credito);
            Context.SaveChanges();
        }

        public void UpdateCredito(CREDITO credito)
        {
            var estadosDetalle = Context.ChangeTracker.Entries<DETALLE_CREDITO>();

            Context.Entry(credito.CLIENTE).State = EntityState.Unchanged;
            Context.Entry(credito).State = EntityState.Modified;

            foreach (var item in credito.DETALLE_CREDITO)
            {
                //item.PRODUCTO.CATEGORIA = null;
                item.PRODUCTO = null;

                Context.Entry(item).State = item.id == Int32.Parse("0") ? System.Data.EntityState.Added : System.Data.EntityState.Modified;
                
                item.ProductoId= item.ProductoId;                
            }
            Context.SaveChanges();
        }

        public bool GetAllCreditosByClienteId(int idCliente)
        {
            var query = from c in Context.CREDITOes.Include("CLIENTE")
                        where c.clienteId.Equals(idCliente) 
                        select c;
            ObjectContext.Refresh(RefreshMode.StoreWins, query);

            return query.Any();
        }

        public List<CREDITO> GetAllFromCreditosSoloDeuda()
        {
            var query = from c in Context.CREDITOes.Include("CLIENTE").Include("DETALLE_CREDITO").Include("DETALLEPAGOes")
                        orderby c.FechaCredito descending
                        where (
                        (c.DETALLE_CREDITO.Where(dcc => dcc.Pagado == false).Sum(dc  => dc.Monto))
                        - (
                        (c.DETALLEPAGOes.Sum(dp => dp.Monto)) - (c.DETALLE_CREDITO.Where(dcc => dcc.Pagado == true).Sum(dc => dc.Monto))
                        ) 
                        ) > 0
                        select c;
            ObjectContext.Refresh(RefreshMode.StoreWins, query);

            return query.ToList();
        }
    }
}
